package com.gxar.quick.ar.server.base.controller;

import com.google.common.collect.Lists;
import com.gxar.common.entity.PageResult;
import com.gxar.common.entity.Result;
import com.gxar.common.entity.SystemCodeEnum;
import com.gxar.common.entity.login.LoginUserThread;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.common.utils.CollectionUtils;
import com.gxar.common.utils.StringUtils;
import com.gxar.quick.ar.server.base.common.properties.WorksProperties;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.exchange.vo.request.AdminExchangeItemTemplateShelvesRequest;
import com.gxar.quick.ar.server.base.model.exchange.vo.response.AdminExchangeItemTemplatePageResponse;
import com.gxar.quick.ar.server.base.reference.UaaReference;
import com.gxar.quick.ar.server.db.service.WorksService;
import com.gxar.uaa.api.dto.user.SysUserId;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/2/27 14:35
 */
@Api(tags = "管理端作品接口")
@RestController
@RequestMapping("/admin/api/works")
@RequiredArgsConstructor
@Slf4j
public class AdminWorksController {

    private final WorksService worksService;

    private final UaaReference uaaReference;

    private final WorksProperties worksProperties;

    @ApiOperation("兑换品模板列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
            @ApiImplicitParam(name = "user_id", value = "用户ID", dataType = "number"),
            @ApiImplicitParam(name = "name", value = "作品名称", dataType = "string"),
    })
    @GetMapping("/exchange-item")
    public Result<PageResult<AdminExchangeItemTemplatePageResponse>> templateList(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                                                  @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                                                  @RequestParam(name = "user_id", required = false) Long userId,
                                                                                  @RequestParam(name = "name", required = false) String name) {
        // 默认查询上架的作品
        Boolean shelves = true;
        List<Long> userIdList = new ArrayList<>();
        if (Objects.isNull(userId) && StringUtils.isBlank(name)) {
            throw new APIRuntimeException(SystemCodeEnum.PARAMETER_MISSING);
        }
        if (StringUtils.isNotBlank(name)) {
            PageResult<SysUserId> userPage = uaaReference.findUserByMenuUrl(pageNum, 100, worksProperties.getCreatorProperties().getMenuUrl(), "GET");
            if (CollectionUtils.isNotEmpty(userPage.getContent())) {
                userIdList.addAll(userPage.getContent().stream().map(SysUserId::getUserId).distinct().collect(Collectors.toList()));
            }
        } else {
            userIdList.add(userId);
        }
        return worksService.worksList(pageNum, pageSize, userIdList, shelves, name);
    }

    @ApiOperation("AR制作作品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
            @ApiImplicitParam(name = "name", value = "作品名称", dataType = "string"),
    })
    @GetMapping("")
    public Result<PageResult<AdminExchangeItemTemplatePageResponse>> arMark(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                                            @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                                            @RequestParam(name = "name", required = false) String name) {
        UserProfile userProfile = LoginUserThread.get();
        List<Long> userIdList = Lists.newArrayList(userProfile.getId());
        return worksService.worksList(pageNum, pageSize, userIdList, null, name);
    }

    @ApiOperation("作品上下架")
    @PutMapping("/{works_id}/shelves")
    public Result<Boolean> shelves(@PathVariable("works_id") Long worksId, @RequestBody @Valid AdminExchangeItemTemplateShelvesRequest request) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        worksService.shelves(userProfile, worksId, request);
        return Result.success("操作成功", true);
    }

    @ApiOperation("作品删除")
    @DeleteMapping("/{works_id}")
    public Result<Boolean> delete(@PathVariable("works_id") Long worksId) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        worksService.deleteWorks(userProfile, worksId);
        return Result.success("操作成功", true);
    }

}
